#!/usr/bin/env python
# -*- coding: UTF-8 -*-
'''
@Project ：BroadviewCoss 
@File    ：middleware.py
@IDE     ：PyCharm 
@Author  ：kdly
@Date    ：2024/12/30 下午6:45 
'''
import logging

from django.http import JsonResponse
from django.utils.deprecation import MiddlewareMixin
from jwt import PyJWTError
from rest_framework_jwt.settings import api_settings

from utils.single_user_login import SingleLogin

logger = logging.getLogger()
# 修改权限
logger.setLevel(logging.INFO)


class JwtAuthenticationMiddleware(MiddlewareMixin):
    def process_request(self, request):
        # 请求白名单
        white_list = [
            '/user/code',
            '/user/client/ip',
            '/user/email/code',
            '/user/update/two/auth'
        ]
        path = request.path
        token = request.META.get('HTTP_AUTHORIZATION')
        if not token:
            token = request.COOKIES.get('token')

        if path not in white_list:
            if path == '/user/login' and request.method == 'POST':
                return
            try:
                jwt_decode_handler = api_settings.JWT_DECODE_HANDLER
                res = jwt_decode_handler(token)
            except PyJWTError as e:
                logger.error(f'jwt认证失败：{e}')
                return JsonResponse({"code": 401, "msg": '认证失败'})

            # ================单用户登录逻辑=====================
            single_login = SingleLogin(res.get('username'))
            if single_login.get_black_list(token):
                return JsonResponse({"code": 401, "msg": '已有用户登录，当前强制下线'})
            # ================单用户登录逻辑=====================
        else:
            return
